package com.atjinggu.jinggumail.order.web;

import com.atjinggu.jinggumail.common.exception.WareStockException;
import com.atjinggu.jinggumail.order.service.OrderService;
import com.atjinggu.jinggumail.order.vo.OrderConfirmVo;
import com.atjinggu.jinggumail.order.vo.OrderSubmitRespVo;
import com.atjinggu.jinggumail.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * @author jingming
 * @Type OrderWebController.java
 * @Desc
 * @date 2021/3/7 21:07
 */
@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;
    @GetMapping("/toTrade")
    public String  toTrade(Model model) throws ExecutionException, InterruptedException {
       OrderConfirmVo orderItem =  orderService.orderConfirm();
       model.addAttribute("orderItem",orderItem);
        return "confirm";
    }

    @PostMapping("/orderSubmit")
    public String orderSubmit(OrderSubmitVo vo, Model model,RedirectAttributes ra){
        try {
            OrderSubmitRespVo respVo = orderService.orderSubmit(vo);
            if (respVo.getCode() == 0) {
                model.addAttribute("order", respVo);
                return "pay";
            } else {
                String msg = "";
                switch (respVo.getCode()) {
                    case 1:
                        msg += "订单过期，请重新刷新后提交";
                        break;
                    case 2:
                        msg += "商品价格发生变化";
                        break;
                }
                ra.addFlashAttribute("msg", msg);
                return "redirect:http://order.jinggumail.com/toTrade";
            }
        }catch (WareStockException e){
            if(e instanceof  WareStockException) {
                ra.addFlashAttribute("msg", e.getMessage());
                return "redirect:http://order.jinggumail.com/toTrade";
            }else {
                ra.addFlashAttribute("msg", "系统异常");
                return "redirect:http://order.jinggumail.com/toTrade";
            }
        }

    }




}